package com.zhku.search.controller;

import com.zhku.base.exception.TaoTaoException;
import com.zhku.search.po.GoodsIndex;
import com.zhku.search.service.IndexService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Api(value = "商品信息索引接口", tags = "商品信息索引接口")
@RestController
@RequestMapping("/index")
public class GoodsIndexController {

    @Value("${elasticsearch.goods.index}")
    private String goodsIndexStore;

    @Autowired
    IndexService indexService;

    @ApiOperation("添加商品索引")
    @PostMapping("goods")
    public Boolean add(@RequestBody GoodsIndex goodsIndex) {

        String goodsId = goodsIndex.getId();
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("商品id为空");
        }
        Boolean result = indexService.addGoodsIndex(goodsIndexStore, goodsId, goodsIndex);
        if (!result) {
            throw new TaoTaoException("添加商品索引失败");
        }
        return result;
    }

    @ApiOperation("修改商品索引")
    @PostMapping("updateGoods")
    public Boolean update(@RequestBody GoodsIndex goodsIndex) {

        String goodsId = goodsIndex.getId();
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("商品id为空");
        }
        Boolean result = indexService.updateGoodsIndex(goodsIndexStore, goodsId, goodsIndex);
        if (!result) {
            throw new TaoTaoException("修改商品索引失败");
        }
        return result;
    }

    @ApiOperation("删除商品索引")
    @PostMapping("deleteGoods")
    public Boolean delete(@RequestBody GoodsIndex goodsIndex) {

        String goodsId = goodsIndex.getId();
        if (StringUtils.isEmpty(goodsId)) {
            throw new TaoTaoException("商品id为空");
        }
        Boolean result = indexService.deleteGoodsIndex(goodsIndexStore, goodsId);
        if (!result) {
            throw new TaoTaoException("删除商品索引失败");
        }
        return result;
    }
}
